# -*- coding: utf-8 -*-

"""
controller for task
"""

from framework.controller import Controller
from models.ufuwa import UFuwaModel
import re
import json
import tornado.httpclient
import tempfile
import os
import pro_rank
import cPickle

class StatCtrl(Controller):
    """task list"""
    def __init__(self, application, request, **kwargs):
        """init"""
        super(StatCtrl, self).__init__(application, request, **kwargs)

    def get(self, *args):
        if not args[0] or args[0] == '/':
            self.write_error(404)
            return
        elif args[0].find('/user/') == 0:
            p = re.match(r'^/user/([0-9]+)$', args[0])
            if not p:
                self.write_error(404)
                return
            u = UFuwaModel()
            data = u.get_fuwas_count(p.group(1))
            for key in data:
                if data.get(key):
                    data[key] = int(data.get(key))
                else:
                    data[key] = 0
            data['hide'] = data['hiding'] + data['caut']
            data['count'] = data['unused'] + data['pack'] + data['hiding']
            self.render('fuwa/stat.html', fuwa=data)
            # self.write(json.dumps(data))
        elif args[0].find('/rank') == 0 or args[0].find('/rank/') == 0:
            p = re.match(r'^/rank/([0-9]+)$', args[0])
            if p:
                user_id = p.group(1)
            else:
                user_id = 0
            self.render('fuwa/rank_ui.html', userid=user_id)
        elif args[0].find('/list') or args[0].find('/list/'):
            msg = dict(err=0, msg='')
            temp = tempfile.gettempdir()
            rank_cache = r"rank"
            rank_cache = os.path.join(temp, '%s.txt' % rank_cache)
            # ranks = list()
            if not os.path.isfile(rank_cache):
                ranks = pro_rank.get_ranks()
            else:
                with open(rank_cache) as fp:
                    ranks = cPickle.load(fp)
            # output
            if not ranks:
                msg['err'] = 1
                msg['msg'] = u'系统繁忙，请稍候再试...'
            msg['data'] = ranks
            self.ajax_out(**msg)
            """  
            mranks = UFuwaModel().get_fuwa_rank()
            ranks = dict()
            # sort users and get user avatar
            for i in [str(x) for x in range(1, 100)]:
                if mranks.get(i):
                    stop = 0
                    tmp_users = set()
                    for user in mranks.get(i)['users']:
                        if user == user_id:
                            current_rank = i
                        if stop < 2:
                            users_avatar.append(user)
                            tmp_users.add(user)
                            stop += 1
                    ranks[i] = dict(num=mranks.get(i)['num'], users=tmp_users)
            # get user info
            if user_id and current_rank:
                users_avatar.append(user_id)
            url = r'https://api.66boss.com/ucenter/userinfo/nick?avatar=1&user_id=%s' % (','.join(users_avatar))
            c = tornado.httpclient.HTTPClient()
            try:
                res = c.fetch(url)
            except tornado.httpclient.HTTPError as e:
                print 'err: %s' % e
                return datas
            c.close()
            j = json.loads(res.body)
            users_avatar = []
            if j['result']:
                users_avatar = j['result']
            self.render('fuwa/rank.html', ranks=ranks, avatar=users_avatar, userid=user_id, c_rank=current_rank)
            """
        else:
            self.write_error(404)
            return
